package server

import (
	"context"
	"errors"
	"gorm.io/gorm"
	__ "user-srv/basic/proto"
	"user-srv/handler/models"
)

// 商品添加
func (s *Server) AddShop(_ context.Context, in *__.AddShopReq) (*__.AddShopResp, error) {
	var shop models.Shop
	shop = models.Shop{
		Img:        in.Img,
		Title:      in.Title,
		Price:      float64(in.Price),
		LowPrice:   float64(in.LowPrice),
		Num:        int(in.Num),
		PriceNum:   int(in.PriceNum),
		SuccessNum: int(in.SuccessNum),
		Limit:      int(in.Limit),
		Remaining:  int(in.Remaining),
	}
	if err := shop.AddShop(); err != nil {
		return nil, errors.New("商品添加失败")
	}
	return &__.AddShopResp{
		ShopId: int64(shop.ID),
	}, nil
}

// 商品展示
func (s *Server) ListShop(_ context.Context, in *__.ListShopReq) (*__.ListShopResp, error) {
	var shop models.Shop
	list, _ := shop.ListShop(int(in.Page), int(in.PageSize), in.Title)
	var listShop []*__.ListShop
	for _, v := range list {
		listShop = append(listShop, &__.ListShop{
			ShopId:     int64(v.ID),
			Img:        v.Img,
			Title:      v.Title,
			Price:      float32(v.Price),
			LowPrice:   float32(v.LowPrice),
			Num:        int64(v.Num),
			PriceNum:   int64(v.PriceNum),
			SuccessNum: int64(v.SuccessNum),
			Limit:      int64(v.Limit),
			Remaining:  int64(v.Remaining),
		})
	}
	return &__.ListShopResp{
		List: listShop,
	}, nil
}

// 修改商品
func (s *Server) UpdateShop(_ context.Context, in *__.UpdateShopReq) (*__.UpdateShopResp, error) {
	var shop models.Shop
	if err := shop.UpdateShop(int(in.ShopId)); err != nil {
		return nil, errors.New("查看商品失败")
	}
	if shop.ID == 0 {
		return nil, errors.New("商品不存在")
	}
	shop = models.Shop{
		Model:      gorm.Model{ID: uint(in.ShopId)},
		Img:        in.Img,
		Title:      in.Title,
		Price:      float64(in.Price),
		LowPrice:   float64(in.LowPrice),
		Num:        int(in.Num),
		PriceNum:   int(in.PriceNum),
		SuccessNum: int(in.SuccessNum),
		Limit:      int(in.Limit),
		Remaining:  int(in.Remaining),
	}
	if err := shop.UpdateShop(int(in.ShopId)); err != nil {
		return nil, errors.New("修改视频失败")
	}
	return &__.UpdateShopResp{
		ShopId: int64(shop.ID),
	}, nil
}
